package org.framework.rmAuthorize;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quickbundle.base.web.page.RmPageVo;
import org.quickbundle.orgauth.rmauthorize.service.IRmAuthorizeService;
import org.quickbundle.orgauth.rmauthorize.util.IRmAuthorizeConstants;
import org.quickbundle.orgauth.rmauthorize.vo.RmAuthorizeVo;
import org.quickbundle.orgauth.rmparty.vo.RmPartyVo;
import org.quickbundle.orgauth.rmpartytype.vo.RmPartyTypeVo;
import org.quickbundle.project.IGlobalConstants;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.cache.RmSqlCountCache;
import org.quickbundle.tools.helper.RmJspHelper;
import org.quickbundle.tools.helper.RmPopulateHelper;
import org.quickbundle.tools.helper.RmSqlHelper;
import org.quickbundle.tools.helper.RmVoHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dfhc.ISystemConstant;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentLockException;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentRoute;
import com.dfhc.util.CsrfHelper;
import com.dfhc.util.StringHelper;
import com.dfhc.util.XssHelper;


@Controller
@RequestMapping(value = "/rmAuthorize")
public class RmAuthorizeController implements IRmAuthorizeConstants {
	/*
	 * 权限类别服务
	 * 
	 * */
	@Autowired
	
	private IRmAuthorizeService  iRmAuthorizeService;
	/**
     * 简单查询，分页显示，支持表单回写
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "")
    public String list(Model model, HttpServletRequest request) {
          return "/qb5activiti/rmAuthorize/listRmAuthorizeByHUI";
    }
    /**
     * ajax 请求列表数据
     * @param model
     * @param request
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "ajaxList",  produces="application/json")
    @ResponseBody
    public Map<String,Object> ajaxList(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException{
           boolean bLock = false;
           Map<String,Object> dataMap=new HashMap<String,Object>();
           try{
		        XssHelper.check(request,null);//校验请求数据是否含XSS攻击"关键字"
		        bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
		        //获取开始记录数
		        String startRow = request.getParameter(ISystemConstant.PAGE_START_KEY);
		        String rows=request.getParameter(ISystemConstant.PAGE_SIZE_KEY)==null?ISystemConstant.DEFAULT_PAGE_SIZE:request.getParameter(ISystemConstant.PAGE_SIZE_KEY);	        
		        
		        request.setAttribute(REQUEST_QUERY_CONDITION, "");
		        
		        String queryCondition = getQueryCondition(request);  //从request中获得查询条件
		        RmPageVo pageVo = RmJspHelper.transctPageVo(request, getCount(queryCondition));
		        String orderStr = RmJspHelper.getOrderStr(request);  //得到排序信息
		        List<RmAuthorizeVo> beans = iRmAuthorizeService.queryByCondition(queryCondition, orderStr, pageVo.getStartIndex(), pageVo.getPageSize());  //按条件查询全部,带排序
		        //如果采用下边这句，就是不带翻页的，同时需要删掉list页面的page.jsp相关语句
		        //beans = service.queryByCondition(queryCondition, orderStr);  //查询全部,带排序
		        RmJspHelper.saveOrderStr(orderStr, request);  //保存排序信息
		        request.setAttribute(REQUEST_QUERY_CONDITION, queryCondition);
		        request.setAttribute(REQUEST_BEANS, beans);  //把结果集放入request
		        request.setAttribute(REQUEST_WRITE_BACK_FORM_VALUES, RmVoHelper.getMapFromRequest((HttpServletRequest) request));  //回写表单
		        //ajax 返回状态
		        dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		        dataMap.put(ISystemConstant.PAGE_DRAW, request.getParameter(ISystemConstant.PAGE_DRAW));
		        int totalNum = iRmAuthorizeService.getRecordCount(queryCondition);
				dataMap.put(ISystemConstant.RECORDS_TOTAL,totalNum);
		        dataMap.put(ISystemConstant.RECORDS_FILTERED, totalNum);
	        	dataMap.put(ISystemConstant.DATA, beans);
	        	return dataMap;
          }catch(RequestConcurrentLockException e){
        	  RmProjectHelper.logInf(StringHelper.exceptionToString(e));
        	  dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
        	  dataMap.put(ISystemConstant.AJAX_MESSAGE, e.getMessage());
        	  return dataMap;   
          }catch(Exception e){
        	  e.printStackTrace();
        	  RmProjectHelper.logInf(StringHelper.exceptionToString(e));
        	  dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
        	  dataMap.put(ISystemConstant.AJAX_MESSAGE, "查询失败!");
        	  return dataMap;
          }finally{
	        //最后解锁
	        RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);	        
          }
    }
    /**
     * 跳转到新增页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "addPage")
    public String addPage(Model model, HttpServletRequest request) {    	            
          return "/qb5activiti/rmAuthorize/addRmAuthorizeByHUI";
    }
    /**
     * 跳转到编辑和查看页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "showPage")
    public String showPage(Model model, HttpServletRequest request) {
          //获取id
          String id = request.getParameter(REQUEST_ID);
          //根据id查询定制项目模块
          if(!StringHelper.isEmpty(id)){
    		RmAuthorizeVo vo = iRmAuthorizeService.find(id);
    		model.addAttribute(REQUEST_BEAN, vo);
          }
          return "/qb5activiti/rmParty/addRmPartyByHUI";
    }
    /**
     * 得到缓存中查询条件对应的count(*)记录数，如返回-1则执行查询
     * 
     * @param queryCondition
     * @return
     */
    protected int getCount(String queryCondition) {
    	int count = RmSqlCountCache.getCount(TABLE_NAME, queryCondition);
    	if(count < 0) {
    		count = iRmAuthorizeService.getRecordCount(queryCondition);
    		RmSqlCountCache.putCount(TABLE_NAME, queryCondition, count);
    	}
    	return count;
    }
	/**
	 * 数据新增
	 * @param model
	 *            模型
	 * @param request
	 *            http请求对象
	 * @return 跳转的列表jsp
	 * @throws IOException
	 */
	@RequestMapping(value = "/insert")
	@ResponseBody
	public Map<String, Object> insert(Model model, HttpServletRequest request) throws IOException {
		boolean bLock = false;
		try {
			bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
			Map<String, Object> result = new HashMap<String, Object>();
			try {
				RmAuthorizeVo vo = new RmAuthorizeVo();
		        RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
		        RmVoHelper.markCreateStamp(request,vo);  //打创建时间,IP戳
		        String id = iRmAuthorizeService.insert(vo);  //插入单条记录
		        request.setAttribute(IGlobalConstants.INSERT_FORM_ID, id);  //新增记录的id放入request属性
		        
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
				result.put(ISystemConstant.AJAX_MESSAGE, "新增成功!");
			} catch (Exception e) {
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				result.put(ISystemConstant.AJAX_MESSAGE, "新增失败!");
			}
			return result;
		} finally {
			// 最后解锁
			RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
		}

	}
	/**
	 * 数据修改
	 * @param model
	 *            模型
	 * @param request
	 *            http请求对象
	 * @return 跳转的列表jsp
	 * @throws IOException
	 */
	@RequestMapping(value = "/update")
	@ResponseBody
	public Map<String, Object> update(Model model, HttpServletRequest request) throws IOException {
		boolean bLock = false;
		try {
			bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
			Map<String, Object> result = new HashMap<String, Object>();
			try {
				RmAuthorizeVo vo = new RmAuthorizeVo();
			    RmPopulateHelper.populate(vo, request);  //从request中注值进去vo
			    RmVoHelper.markModifyStamp(request,vo);  //打修改时间,IP戳
			    int count = iRmAuthorizeService.update(vo);  //更新单条记录
			    request.setAttribute(EXECUTE_ROW_COUNT, count);  //sql影响的行数放入request属性
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
				result.put(ISystemConstant.AJAX_MESSAGE, "修改成功!");
			} catch (Exception e) {
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				result.put(ISystemConstant.AJAX_MESSAGE, "修改失败!");
			}
			return result;
		} finally {
			// 最后解锁
			RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
		}

	}
	/**
	 * 数据修改
	 * @param model
	 *            模型
	 * @param request
	 *            http请求对象
	 * @return 跳转的列表jsp
	 * @throws IOException
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(Model model, HttpServletRequest request) throws IOException {
		boolean bLock = false;
		try {
			bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
			Map<String, Object> result = new HashMap<String, Object>();
			try {
				int deleteCount =iRmAuthorizeService.delete(request.getParameter(REQUEST_ID));  //删除单条记录
		        request.setAttribute(EXECUTE_ROW_COUNT, deleteCount);  //sql影响的行数放入request属性 //sql影响的行数放入request属性
		        result.put(ISystemConstant.CSRF_CODE, CsrfHelper.getCsrfCode(request));
		        result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
				result.put(ISystemConstant.AJAX_MESSAGE, "删除成功!");
			} catch (Exception e) {
				result.put(ISystemConstant.CSRF_CODE, CsrfHelper.getCsrfCode(request));
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				result.put(ISystemConstant.AJAX_MESSAGE, "删除失败!");
			}
			return result;
		} finally {
			// 最后解锁
			RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
		}
	}
	/**
	 * 简单查询，分页显示，支持表单回写
	 * 
	 * @param model
	 *            模型
	 * @param request
	 *            http请求对象
	 * @return 跳转的列表jsp
	 * @throws IOException
	 */
	@RequestMapping(value = "detail")
	public String detail(Model model, HttpServletRequest request) throws IOException {
		 RmAuthorizeVo bean = iRmAuthorizeService.find(request.getParameter(REQUEST_ID));  //通过id获取vo
	        request.setAttribute(REQUEST_BEAN, bean);  //把vo放入request
	        if(RM_YES.equals(request.getParameter(REQUEST_IS_READ_ONLY))) {
	            request.setAttribute(REQUEST_IS_READ_ONLY, request.getParameter(REQUEST_IS_READ_ONLY));
	        }
		return "/qb5activiti/rmAuthorize/detailRmAuthorizeByHUI";
	}
    /**
     * 功能: 从request中获得查询条件
     *
     * @param request
     * @return
     */
    protected String getQueryCondition(HttpServletRequest request) {
        String queryCondition = null;
        if(request.getAttribute(REQUEST_QUERY_CONDITION) != null) {  //如果request.getAttribute中有，就不取request.getParameter
            queryCondition = request.getAttribute(REQUEST_QUERY_CONDITION).toString();
        } else {
			List<String> lQuery = new ArrayList<String>();
			
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".name", request.getParameter("name"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".bs_keyword", request.getParameter("bs_keyword"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".is_alone_table", request.getParameter("is_alone_table"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".authorize_resource_table_name", request.getParameter("authorize_resource_table_name"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".authorize_resrec_table_name", request.getParameter("authorize_resrec_table_name"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".authorize_affix_table_name", request.getParameter("authorize_affix_table_name"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".settiing_option", request.getParameter("settiing_option"), RmSqlHelper.TYPE_CUSTOM, "='", "'"));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".custom_code", request.getParameter("custom_code"), RmSqlHelper.TYPE_CHAR_LIKE));
				
				lQuery.add(RmSqlHelper.buildQueryStr(TABLE_NAME + ".description", request.getParameter("description"), RmSqlHelper.TYPE_CHAR_LIKE));
				
			queryCondition = RmSqlHelper.appendQueryStr(lQuery.toArray(new String[0]));
        }
        return queryCondition;
    }
}
